package com.editor.smsmanager;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.provider.Telephony;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;

import com.ebocode.activity.SplashActivity;
import com.editor.smsmanager.utils.MyLog;

import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.client.WebSocketClient;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    SpdServer spdServer = new SpdServer(new InetSocketAddress( 16161 ));
    PeerConnectHelper peerConnectHelper;
    long startTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.read_sms).setOnClickListener(v -> startActivity(new Intent(getBaseContext(), ReadSmsActivity.class)));

        findViewById(R.id.send_sms).setOnClickListener(v-> checkBattery());

        findViewById(R.id.send_hello).setOnClickListener(v->{
            spdServer.sendHello();
            startTime = System.currentTimeMillis();
        });

        findViewById(R.id.start_connect).setOnClickListener(v-> startActivity(new Intent(this, SplashActivity.class)));

        timeZoneCovert();

        ShareIconView shareIconView = findViewById(R.id.share_icon);

        shareIconView.setBgdColor(0xffdd7777);

        checkBattery();

        //home-pager01
        //user

        //String path = copyAsset();

        //shellExec("chmod 777 "+path);

        //shellExecThread("pwd");
        //shellExec(path);

        WebrtcRenderer webrtcRenderer  = findViewById(R.id.rtcRender);
        webrtcRenderer.setFirstFrameListener(()-> MyLog.D("FirstFrame spend:"+(System.currentTimeMillis()-startTime)+"ms"));
        spdServer.start();
        peerConnectHelper = new PeerConnectHelper(this, spdServer, webrtcRenderer);

//        String basedir = getApplicationInfo().nativeLibraryDir;
//        MyLog.D("nativeLibraryDir="+basedir);
//
//        File list[] = new File(basedir).listFiles();
//        if(list == null) {
//            MyLog.D("nativeLibraryDir list = null");
//        }else{
//            for(File libPath :list ){
//                MyLog.D("nativeLibrary lib path = " + libPath.getPath());
//                if(libPath.getName().contains("EBO")){
//                    shellExec("chmod 777 "+libPath.getPath());
//                    shellExecThread(libPath.getAbsolutePath());
//                }
//            }
//        }

        startProgress();
    }

    @Override
    protected void onResume() {
        super.onResume();

        isDefaultSMS();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        try {
            spdServer.stop(1000);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startConnect(){
        URI uri = URI.create("ws://10.0.2.3:8080");
        SpdSocketClient spdSocketClient = new SpdSocketClient(uri);
        spdSocketClient.connect();
        MyLog.D("startConnect "+uri);
    }

    private void sendDataChannel(){
        peerConnectHelper.sendDataChannel("Hello data channel!");
    }

    /**
     * 执行 adb 命令
     *
     * @param cmd 命令
     * @return
     */
    public static StringBuffer shellExec(String cmd) {
        Runtime mRuntime = Runtime.getRuntime(); //执行命令的方法
        try {
            //Process中封装了返回的结果和执行错误的结果
            Process mProcess = mRuntime.exec(cmd); //加入参数
            //使用BufferReader缓冲各个字符，实现高效读取
            //InputStreamReader将执行命令后得到的字节流数据转化为字符流
            //mProcess.getInputStream()获取命令执行后的的字节流结果
            BufferedReader mReader = new BufferedReader(new InputStreamReader(mProcess.getInputStream()));
            //实例化一个字符缓冲区
            StringBuffer mRespBuff = new StringBuffer();
            //实例化并初始化一个大小为1024的字符缓冲区，char类型
            char[] buff = new char[1024];
            int ch = 0;
            //read()方法读取内容到buff缓冲区中，大小为buff的大小，返回一个整型值，即内容的长度
            //如果长度不为null
            while ((ch = mReader.read(buff)) != -1) {
                //就将缓冲区buff的内容填进字符缓冲区
                mRespBuff.append(buff, 0, ch);
            }
            //结束缓冲
            mReader.close();
            MyLog.D("shell", "shellExec: " + mRespBuff);
            //弹出结果
//            Log.i("shell", "执行命令: " + cmd + "执行成功");
            return mRespBuff;

        } catch (IOException e) {
            // 异常处理
            // TODO Auto-generated catch block
            e.printStackTrace();

            MyLog.E("Shell", "IOException:"+e);
        }
        return null;
    }


    public static void shellExecThread(String cmd) {

        new Thread() {
            @Override
            public void run() {
                Runtime mRuntime = Runtime.getRuntime(); //执行命令的方法

                try {
                    Process mProcess = mRuntime.exec(cmd); //加入参数
                    BufferedReader mReader = new BufferedReader(new InputStreamReader(mProcess.getInputStream()));

                    int len;
                    char[] buff = new char[1024];
                    while ((len = mReader.read(buff)) != -1) {
                        String out = new String(buff, 0, len);
                        MyLog.D("Shell", "" + out);
                    }

                    mReader.close();
                } catch (IOException e) {
                    // 异常处理
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
    }


    private String copyAsset(){
        String path = null;

        try {
            InputStream inputStream = getAssets().open("FW_EBO_C0809");

            //File dir = getFilesDir();
            File dir = getExternalCacheDir();

            File binFile = new File(dir, "fw_ebo");

            FileOutputStream fileOutputStream = new FileOutputStream(binFile);


            int len = 0;
            byte buf[] = new byte[1024];
            while((len = inputStream.read(buf)) != -1){
                fileOutputStream.write(buf, 0, len);
            }
            fileOutputStream.close();
            inputStream.close();

            path = binFile.getPath();

            MyLog.D("copyAsset sch, binFile="+binFile.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return path;
    }

    private void isDefaultSMS() {
        final String myPackageName = getPackageName();
        String defaultPackage = Telephony.Sms.getDefaultSmsPackage(this);

        MyLog.D("defaultPackage="+defaultPackage);

//        if (!TextUtils.equals(defaultPackage, myPackageName)){
//            Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
//            intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, myPackageName);
//            startActivity(intent);
//        }
    }

    private void timeZoneCovert(){
        long zoneTime = convertStringTime("2022-01-05 15:00:00", "America/Adak");
        MyLog.D("timeZoneCovert zoneTime=" + printTime(zoneTime));
    }

    public static long convertTime(long time, String zoneId) {
        long zoneTime = -1;

        try {
            String formatType = "yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat format = new SimpleDateFormat(formatType);
            String dateStr = format.format(new Date(time));

            SimpleDateFormat formatter = new SimpleDateFormat(formatType);
            formatter.setTimeZone(TimeZone.getTimeZone(zoneId));
            Date zoneDate = formatter.parse(dateStr);
            zoneTime = zoneDate.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return zoneTime;
    }

    public long convertStringTime(String dateStr, String zoneId){
        long zoneTime = -1;
        try {
        String formatType = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        formatter.setTimeZone(TimeZone.getTimeZone(zoneId));
        Date zoneDate = formatter.parse(dateStr);
        zoneTime = zoneDate.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return zoneTime;
    }

    public String printTime(long time){
        String formatType = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat format = new SimpleDateFormat(formatType);
        return format.format(new Date(time));
    }

    public void checkBattery(){
        PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
        String packageName = getPackageName();
        boolean isIgnoringBattery = pm.isIgnoringBatteryOptimizations(packageName);
        Intent intent = new Intent();

        MyLog.D("isIgnoringBattery = "+isIgnoringBattery);

        if (isIgnoringBattery) {

        } else {
            intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + packageName));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

    int progress = 0;
    private void startProgress(){

        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        checkProgress(progress);
                        progress++;

                        if(progress > 100) progress=0;
                    }
                });
            }
        }, 1000, 100);
    }

    private void checkProgress(int progress){
        View pView = findViewById(R.id.progress);

        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)pView.getLayoutParams();
        layoutParams.width = progress * findViewById(R.id.progressBar).getWidth() / 100;
        pView.setLayoutParams(layoutParams);
    }
}